import type {
  AddSignRequest,
  ApprovalTaskListResponse,
  ApproveRequest,
  CopyPageRequest,
  CopyPageResponse,
  DelegateRequest,
  MyProcessPageRequest,
  MyProcessPageResponse,
  ProcessInstance,
  ProcessInstanceInfo,
  RejectRequest,
  TaskItem,
  TaskPageRequest,
  TaskPageResponse,
  TransferRequest,
} from '@/api/types/workflow'
import { ref } from 'vue'
import * as workflowApi from '@/api/workflow'
import { useUserStore } from '@/store/user'

// 流程名称到页面路径的映射配置
export const PROCESS_NAME_TO_PATH = {
  '物流-运单制作审批': '/pages-bs/ShippingOrderApproval/detail',
  '物流-业务费用': '/pages-bs/BusinessExpense/detail',
  '物流-后台手工登记往来账': '/pages-bs/ManualRegistrationOfAccounts/detail',
  '物流-账单结算': '/pages-bs/BillSettlement/detail',
  '物流-本方定金': '/pages-bs/PaymentOfDeposit/detail',
  '物流-本方保证金': '/pages-bs/PaymentOfSecurityDeposit/detail',
  '物流-定金保证金释放': '/pages-bs/ReleaseOfSecurityDeposit/detail',
  '物流-预支申请': '/pages-bs/AdvancePaymentApplication/detail',
  '物流-费用报销': '/pages-bs/ExpenseReimbursement/detail',
  '物流-退款申请': '/pages-bs/RefundApplication/detail',
  '物流-付款申请': '/pages-bs/PaymentRequest/detail',
  '物流-财务付款': '/pages-bs/FinancialPayment/detail',
  '物流-后台登记资金': '/pages-bs/BackgroundRegistrationOfFunds/detail',
  '物流-资金退款': '/pages-bs/FundRefund/detail',
  '物流-资金认领': '/pages-bs/FundClaim/detail',
  '物流-发票申请': '/pages-bs/InvoiceApplication/detail',
  '物流-资金调拨': '/pages-bs/FundTransfer/detail',
  '物流-合同创建': '/pages-bs/ContractCreation/detail',
  '物流-项目创建': '/pages-bs/ProjectCreation/detail',
  '物流-外收承兑汇票': '/pages-bs/OtherReceivedAcceptanceBill/detail',
  '物流-开立承兑汇票': '/pages-bs/OpenAcceptanceBill/detail',
  '物流-其他实付': '/pages-bs/OtherPayment/detail',
  '物流-其他实收': '/pages-bs/OtherReceived/detail',
}

/**
 * 获取流程实例对应的页面路径
 * @param taskName 任务名称
 * @param processInstanceId 流程实例ID
 * @param flowId 流程定义ID
 * @returns 完整的页面路径（包含查询参数）
 */
export function getProcessDetailPath(
  taskName?: string,
  processInstanceId?: string,
  flowId?: string,
): string {
  // 默认路径
  let targetPath = '/pages-fg/404/index'
  // 否则根据任务名称匹配
  if (taskName && PROCESS_NAME_TO_PATH[taskName]) {
    targetPath = PROCESS_NAME_TO_PATH[taskName]
  }

  // 获取流程实例ID（优先使用传入的参数，否则从processInstance对象中获取）
  const instanceId = processInstanceId || ''

  // 添加流程实例ID作为查询参数
  return `${targetPath}?id=${instanceId}&flowId=${flowId}`
}

/**
 * 流程管理Hook
 * 提供流程实例、任务处理、流程状态等相关功能
 */
export function useFlow() {
  const currentProcess = ref<ProcessInstance | null>(null)
  const currentTask = ref<TaskItem | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 列表数据状态
  const todoTasks = ref<TaskPageResponse | null>(null)
  const completedTasks = ref<TaskPageResponse | null>(null)
  const copiedProcesses = ref<CopyPageResponse | null>(null)
  const myProcesses = ref<MyProcessPageResponse | null>(null)
  const todoCount = ref<number | string | null>(null)

  /**
   * 获取流程实例详情
   * @param processId 流程实例ID
   */
  const getProcessInstance = async (processId: string) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getProcessInstance(processId)
      currentProcess.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取流程实例失败'
      console.error('获取流程实例失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取待办任务列表
   * @param params 查询参数
   */
  const getTodoTaskPage = async (params: TaskPageRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getTodoTaskPage(params)
      todoTasks.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取待办任务列表失败'
      console.error('获取待办任务列表失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取已完成任务列表
   * @param params 查询参数
   */
  const getCompletedTaskPage = async (params: TaskPageRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getCompletedTaskPage(params)
      completedTasks.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取已完成任务列表失败'
      console.error('获取已完成任务列表失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取抄送列表
   * @param params 查询参数
   */
  const getCopyPage = async (params: CopyPageRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getCopyPage(params)
      copiedProcesses.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取抄送列表失败'
      console.error('获取抄送列表失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取我发起的列表
   * @param params 查询参数
   */
  const getMyProcessPage = async (params: MyProcessPageRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getMyProcessPage(params)
      myProcesses.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取我发起的列表失败'
      console.error('获取我发起的列表失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取待办数量
   */
  const getTodoCount = async () => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getTodoCount()
      todoCount.value = res.data
      return res
    }
    catch (err) {
      error.value = '获取待办数量失败'
      console.error('获取待办数量失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 审批同意
   * @param data 审批参数
   */
  const approveTask = async (data: ApproveRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.approveTask(data)
      return res.data
    }
    catch (err) {
      error.value = '审批同意失败'
      console.error('审批同意失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 审批拒绝
   * @param data 拒绝参数
   */
  const rejectTask = async (data: RejectRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.rejectTask(data)
      return res.data
    }
    catch (err) {
      error.value = '审批拒绝失败'
      console.error('审批拒绝失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 委派任务
   * @param data 委派参数
   */
  const delegateTask = async (data: DelegateRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.delegateTask(data)
      return res.data
    }
    catch (err) {
      error.value = '委派任务失败'
      console.error('委派任务失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 转派任务
   * @param data 转派参数
   */
  const transferTask = async (data: TransferRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.transferTask(data)
      return res.data
    }
    catch (err) {
      error.value = '转派任务失败'
      console.error('转派任务失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 加签任务
   * @param data 加签参数
   */
  const addSignTask = async (data: AddSignRequest) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.addSignTask(data)
      return res.data
    }
    catch (err) {
      error.value = '加签任务失败'
      console.error('加签任务失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 获取流程定义信息
   * @param processDefinitionId 流程定义ID
   */
  const getProcessDefinition = async (processDefinitionId: string) => {
    loading.value = true
    error.value = null
    try {
      const res = await workflowApi.getProcessDefinition({ id: processDefinitionId })
      return res.data
    }
    catch (err) {
      error.value = '获取流程定义失败'
      console.error('获取流程定义失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  /**
   * 根据流程名称获取对应的页面路径
   * @param processName 流程名称
   */
  const getProcessPathByProcessName = (processName: string): string | null => {
    const PROCESS_NAME_TO_PATH: Record<string, string> = {
      '运单制作审批': '/pages-bs/ShippingOrderApproval/detail',
      '物流-业务费用': '/pages-bs/BusinessExpense/detail',
      '后台手工登记往来账': '/pages-bs/ManualRegistrationOfAccounts/detail',
      '账单结算': '/pages-bs/BillSettlement/detail',
      '本方定金': '/pages-bs/PaymentOfDeposit/detail',
      '本方保证金': '/pages-bs/PaymentOfSecurityDeposit/detail',
      '定金保证金释放': '/pages-bs/ReleaseOfSecurityDeposit/detail',
      '费用报销': '/pages-bs/ExpenseReimbursement/detail',
      '退款申请': '/pages-bs/RefundApplication/detail',
      '付款申请': '/pages-bs/PaymentRequest/detail',
      '财务付款': '/pages-bs/FinancialPayment/detail',
      '物流-后台登记资金': '/pages-bs/BackgroundRegistrationOfFunds/detail',
      '资金退款': '/pages-bs/FundRefund/detail',
      '资金认领': '/pages-bs/FundClaim/detail',
      '发票申请': '/pages-bs/InvoiceApplication/detail',
      '物流-资金调拨': '/pages-bs/FundTransfer/detail',
      '物流-合同创建': '/pages-bs/ShippingOrderApproval/detail',
      '物流-项目创建': '/pages-bs/ProjectCreation/detail',
      '物流-外收承兑汇票': '/pages-bs/OtherReceivedAcceptanceBill/detail',
      '物流-开立承兑汇票': '/pages-bs/OpenAcceptanceBill/detail',
      '物流-其他实付': '/pages-bs/OtherPayment/detail',
      '物流-其他实收': '/pages-bs/OtherReceived/detail',
    }

    return PROCESS_NAME_TO_PATH[processName] || null
  }

  /**
   * 导航到流程详情页面
   * @param processInstance 流程实例对象
   * @param taskId 任务ID
   */
  const navigateToProcessDetail = (processInstance: ProcessInstanceInfo, taskId?: string) => {
    if (!processInstance || !processInstance.name) {
      console.error('流程实例信息不完整')
      return
    }

    const path = getProcessPathByProcessName(processInstance.name)
    if (path) {
      const targetId = taskId || processInstance.id
      uni.navigateTo({
        url: `${path}?id=${targetId}`,
        fail: (err) => {
          console.error('导航失败:', err)
          uni.showToast({
            title: '导航失败，请重试',
            icon: 'none',
          })
        },
      })
    }
    else {
      // 默认导航到通用审批页面
      uni.navigateTo({
        url: `/pages/approval/approve?id=${processInstance.id || ''}`,
      })
    }
  }

  /**
   * 重置状态
   */
  const reset = () => {
    currentProcess.value = null
    currentTask.value = null
    todoTasks.value = null
    completedTasks.value = null
    copiedProcesses.value = null
    myProcesses.value = null
    todoCount.value = null
    error.value = null
  }

  /**
   * 导航到流程记录页面
   * @param processInstance 流程实例对象
   */
  const navigateToProcessRecords = (id: string) => {
    if (!id) {
      console.error('流程实例ID不完整')
      return
    }
    uni.navigateTo({
      url: `/pages/approval/process?id=${id || ''}`,
      fail: (err) => {
        console.error('导航失败:', err)
        uni.showToast({
          title: '导航失败，请重试',
          icon: 'none',
        })
      },
    })
  }

  /**
   * 获取当前用户待审批任务ID
   * @param processInstanceId 流程实例ID
   * @returns 符合条件的审批任务ID或null
   */
  const getCurrentUserPendingTaskId = async (processInstanceId: string): Promise<string | null> => {
    loading.value = true
    error.value = null
    try {
      const userStore = useUserStore()
      const loginUserId = userStore.userInfo.userInfo.id || ''

      if (!loginUserId) {
        console.error('当前用户ID为空')
        return null
      }

      const res = await workflowApi.getApprovalTaskList(processInstanceId)
      const approvalTasks = res.data || []

      // 过滤条件：
      // 1. assigneeUser.id 与登录用户ID相同
      // 2. status 为 1（待审批）
      const filteredTask = approvalTasks.find((task) => {
        return task.assigneeUser?.id === loginUserId && task.status === 1
      })

      // 返回符合条件的任务ID，否则返回null
      return filteredTask?.id || null
    }
    catch (err) {
      error.value = '获取审批信息列表失败'
      console.error('获取审批信息列表失败:', err)
      throw err
    }
    finally {
      loading.value = false
    }
  }

  return {
    // 状态
    currentProcess,
    currentTask,
    loading,
    error,
    todoTasks,
    completedTasks,
    copiedProcesses,
    myProcesses,
    todoCount,

    // 方法
    getProcessInstance,
    getTodoTaskPage,
    getCompletedTaskPage,
    getCopyPage,
    getMyProcessPage,
    getTodoCount,
    approveTask,
    rejectTask,
    delegateTask,
    transferTask,
    addSignTask,
    getProcessDefinition,
    getProcessPathByProcessName,
    navigateToProcessDetail,
    reset,
    navigateToProcessRecords,
    getCurrentUserPendingTaskId,
    // 导出映射配置和路径获取函数
    PROCESS_NAME_TO_PATH,
    getProcessDetailPath,
  }
}

export default useFlow
